<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/25/17
 * Time: 4:50 PM
 */
declare(strict_types=1);


namespace wshore\helper;

/**
 * Class PHPDatabase PHP数据库
 * @package wshore\helper
 */
class PHPDatabase
{

    private static $_cache = [];

    /**
     * @param string $identify
     * @param mixed $replacement 缓存不存在时的替代
     * @return mixed
     */
    public static function get(string $identify, $replacement = [])
    {
        if (!isset(self::$_cache[$identify])) {
            $file = WS_PATH_RUNTIME . "/rawtemp/{$identify}.tmp";
            if (is_file($file) and is_readable($file)) {
                self::$_cache[$identify] = include $file;
            } else {
                self::$_cache[$identify] = $replacement;
            }
        }
        return self::$_cache[$identify];
    }

    /**
     * @param $identify
     * @param array $data
     * @return void
     */
    public static function set(string $identify, array $data)
    {
        self::$_cache[$identify] = $data;
    }

    /**
     * 保存运行时配置
     */
    public static function save()
    {
        foreach (self::$_cache as $identify => $data) {
            $file = WS_PATH_RUNTIME . "/rawtemp/{$identify}.tmp";//缓存文件名称
            $dirname = dirname($file);
            mkdir($dirname, 0777, true);
            touch($file);
            if (!file_put_contents($file, '<?php return ' . var_export($data, true) . ';')) {
                return false;
            }
        }
        return true;
    }

}

register_shutdown_function(function () {
    PHPDatabase::save();
});